package com.zbcz.erp.util

import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import com.zbcz.erp.bean.FileItem
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

class UploadFileUtils {

    fun getFileFromUri(context: Context, uri: Uri): File? {
        val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = context.contentResolver.query(uri, filePathColumn, null, null, null)
        cursor?.moveToFirst()
        val columnIndex = cursor?.getColumnIndex(filePathColumn[0])
        val filePath = cursor?.getString(columnIndex ?: 0)
        cursor?.close()
        return filePath?.let { File(it) }
    }

    suspend fun uploadFiles(context: Context, fileItems: List<FileItem>) {
        fileItems.forEach { fileItem ->
            fileItem.uri?.let { uri ->
                val file = getFileFromUri(context, uri)
                file?.let {
                    val requestFile = it.asRequestBody("multipart/form-data".toMediaTypeOrNull())
                    val body = MultipartBody.Part.createFormData("file", it.name, requestFile)
//                    val response = RetrofitClient.instance.uploadFile(body)
//                    if (response.isSuccessful) {
//                        println("Upload successful: ${response.body()}")
//                    } else {
//                        println("Upload failed: ${response.errorBody()}")
//                    }
                }
            }
        }
    }

}